<template>
  <div id="Login">
    <div class="header">
      <div>智能电表管理平台</div>
    </div>
    <div class="main">
      <div class="login">
        <div class="title">请输入用户和密码</div>

        <!-- 登录表单 -->
        <el-form class="LoginForm"
                 :model="loginForm"
                 :rules="rules"
                 ref="loginForm"
                 >
          <el-form-item prop="email">
            <el-input placeholder="用户"
                      prefix-icon="el-icon-user"
                      v-model="loginForm.email">
            </el-input>
          </el-form-item>

          <el-form-item prop="password">
            <el-input placeholder="密码"
                      prefix-icon="el-icon-unlock"
                      show-password
                      v-model="loginForm.password">
            </el-input>
          </el-form-item>
          <div class="tips">
            <router-link :to="{name:'ForgotPassword'}">
              <el-link class="tip_1">忘记密码？</el-link>
            </router-link>

              <router-link :to="{name:'Register'}">
                <el-link class="tip_2">没有账号，注册<i class="el-icon-arrow-right"></i></el-link>
              </router-link>
          </div>
          <el-form-item>
            <el-button type="primary"
                       size="medium"
                       :loading="btnLoading"
                       @click="login(loginForm)">登 录</el-button>
          </el-form-item>

        </el-form>
      </div>
    </div>
    <div class="footer">
    </div>
  </div>
</template>

<script>
import { postLogin } from "api/login/login";
import { mapMutations } from 'vuex';
import router from "@/router";
import {getCampusList} from "@/api/other/campusList";
import {getBuildingList} from "@/api/schoolManage/buildingManage"

export default {
  data() {
    return {
      loginForm: {
        email: '',
        password: ''
      },
      rules: {
        email: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          {
            min: 3,
            max: 30,
            type:'email',
            message: '请输入正确的邮箱号',
            trigger:[ 'blur','change']
          }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
        ]
      },
      // 登录按钮 加载状态
      btnLoading: false
    }
  },
  methods: {
    login(loginForm) {
      //进入规则验证
      this.$refs.loginForm.validate((valid)=>{
        //验证成功
        if(valid){
           // 开启登录加载按钮状态
     this.btnLoading = true
      postLogin(loginForm)
      .then(res => {
        const resData = res.data;
        if(resData.success){
          this.CampusList();
          this.buildingList();
          this.$message({
            message: resData.message,
            type: 'success',
            center:true
          });

          window.sessionStorage.setItem(
              'Authorization',
            resData.data.token
          );
          window.sessionStorage.setItem(
            "userID",
            resData.data.webUserId
          );
            this.allMenu = this.menuDataFormat(resData.data.menu);
            this.getAllMenu(this.allMenu);
            this.getUserName(resData.data.username);
            this.getUserEmail(this.loginForm.email);
            //通过vuex状态管理保存的活动标签实现返回最后一次打开的标签页
            this.handleRedirect(this.$store.state.aside.isActive)

         }
        else{
          this.btnLoading = false;
           return this.$message({
            message: resData.message,
            type: 'error',
             center:true
          });
         }
         // 结束登录按钮加载状态

      })
      .catch((err) => {
        console.log(err);
          this.$message({
            message: "无法连接到服务器",
            type: 'error'
          });
          // 结束登录按钮加载状态
          this.btnLoading = false;
      })
        }
        else{
          return false;
        }
      })
     
    },
    ...mapMutations({
      getAllMenu: 'getAllMenu',
      getUserName: 'getUserName',
      getUserEmail:'getUserEmail',
      getCampus:'getCampus',
      getBuildingList:'getBuilding'
    }),
     // 数据处理
    menuDataFormat (arr)
{
      const data = [];
      for (const item of arr) {
        const cArr = [];
        for (const cItem of item.subMenu) {
          cArr.push({
            id: cItem.menuId,
            label: cItem.menuName,
            name: cItem.menuName,
            path: cItem.path,
            icon: cItem.icon
          });
        }

      if (cArr.length < 1 ){
        data.push({
          id: item.menuId,
          label: item.menuName,
          name: item.menuName,
          path: item.path,
          icon: item.icon,
        });}else {
        data.push({
          id: item.menuId,
          label: item.menuName,
          name: item.menuName,
          path: item.path,
          icon: item.icon,
          children: cArr
        });
      }

      }
      return data;
    },
    CampusList()
      {
      getCampusList().then(res=>{
        if (res.data.code == 200){
          const list =res.data.data;
         return this.getCampus(list);
        }
      }).catch(()=>{


      })
    },
    //获取楼栋列表
    buildingList(){
      getBuildingList(1,10).then(res=>{
        if (res.data.code == 200){
          const list = res.data.data.records;
          return this.getBuildingList(list);
        }
      })
},
    // 路由重定向
    handleRedirect(routerName){
      const list = this.$store.state.aside.openedTab;
      if (routerName === ''){
        //第一次登录
        this.$store.commit('setActiveItem','首页');
        return router.push({path:'/index'});
      }
      else
      {
        //之前登录过或登出
        list.forEach(item => {
          if (item.label === routerName) {
            //前往该页面
            router.push({path: `${item.path}`})

          }
        })
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.router-link-active {
  text-decoration: none;
}

#Login {
  width: 100%;

  box-sizing: border-box;
  .header {
    margin-top: 0px;
    padding-top: 5%;
    font-size: 36px;
    font-weight: 600;
    text-align: center;
  }
  .main {
    width: 100%;
    height: 50%;
    position: absolute;
    bottom: 20%;
    left: 0;
    background-image: url(~assets/img/login/illustrations.svg);
    background-repeat: no-repeat;
    background-size: 300px 300px;
    background-position: 90% 80%;
    .login{
      //backdrop-filter: blur(10px);
      position: absolute;
      top: 40%;
      left: 50%;
      transform: translate(-50%, -50%);
      width: 500px;
      height: 300px;
      border-radius: 10px;
      background-color: rgba(255,255,255,0.5);
      box-shadow: 0px 0px 10px 1px rgba(80, 80, 80, 0.2);
      .title {
          font-size: 18px;
          color: #666;
          text-align: center;
          margin-top: 5%;
        }
      .LoginForm {
        width: 60%;
        margin: 30px 100px;
        box-sizing: border-box;
        border-radius: 10px;
      }
      .tips {
        color: #666;
        position: relative;
        margin-bottom: 10px;

        .tip_2 {
          position:absolute;
          right: 0;
        }
      }
      .tips a{
        text-decoration: none;
      }
    }
  }
  .footer{
    width: 100%;
    height: 20%;
    background-image: url(~assets/img/login/footer.svg);
    background-repeat: no-repeat;
    position: absolute;
    bottom: 0;
    left: 0;
  }
}

/deep/ .el-button {
  width: 100%;
}

</style>
